package com.android.webcamsViewer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;

/**
 * Activity WebcamView
 * 
 * @author irodriguez
 * 
 */
public class WebcamView extends Activity {
	// Static attributes
	// Dialogs
	private static final int PROGRESS_DIALOG = 0;
	private static final int REMOVE_DIALOG = 1;

	// Activities
	private static final int WEBCAM_EDIT = 0;
	private static final int WEBCAM_REFRESH = 1;
	private static final int WEBCAM_REMOVE = 2;
	private static final String TAG = "WebcamView";

	// Attributes
	private ProgressDialog progressDialog = null;
	private AlertDialog alertDialog = null;
	private WebcamList list = null;
	private ImageView imageView = null;
	private Bitmap bm = null;
	private int position;

	/**
	 * Handler onCreate event
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view);
		Bundle extras = getIntent().getExtras();
		// Get position of selected image
		position = extras.getInt("position");
		// Load url and names list
		list = new WebcamList(this.getApplicationContext());

		imageView = (ImageView) findViewById(R.id.image);
		launchActivity(WEBCAM_REFRESH);
	}

	/**
	 * Handler onCreateDialog event
	 */
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			progressDialog = new ProgressDialog(WebcamView.this);
			progressDialog.setMessage(getText(R.string.loading));
			// New thread to execute refresh
			return progressDialog;
		case REMOVE_DIALOG:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getText(R.string.msgRemove));
			builder.setCancelable(false);
			builder.setPositiveButton(getText(R.string.yes),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
							launchActivity(WEBCAM_REMOVE);
						}
					});
			builder.setNegativeButton(getText(R.string.no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			alertDialog = builder.create();
			return alertDialog;
		default:
			return null;
		}
	}

	/**
	 * Handler event onCreateOptionsMenu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_view, menu);
		return true;
	}

	/**
	 * Handler event onOptionsItemSelect
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		// Create new activity with add form
		case R.id.edit:
			launchActivity(WEBCAM_EDIT);
			return true;
		case R.id.delete:
			launchActivity(WEBCAM_REMOVE);
			return true;
		default:
			return true;
		}

	}

	/**
	 * 
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			switch (requestCode) {
			case WEBCAM_EDIT:
				launchActivity(WEBCAM_REFRESH);
				Intent i = new Intent();
				i.putExtra("refresh", true);
				setResult(RESULT_OK, i);
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 
	 */
	public void launchActivity(int activity) {
		Intent i = null;
		switch (activity) {
		case WEBCAM_EDIT:
			i = new Intent(this, WebcamAdder.class);
			i.putExtra("position", position);
			startActivityForResult(i, WEBCAM_EDIT);
			return;
		case WEBCAM_REFRESH:
			// Set title of view
			setTitle(list.getWebcam(position).getName());
			// Asynchronous task
			DownloadImageTask task = new DownloadImageTask();
			task.execute(list.getWebcam(position).getUrl());
			return;
		case WEBCAM_REMOVE:
			showDialog(REMOVE_DIALOG);
			list = new WebcamList(this);
			list.removeWebcam(position);
			dismissDialog(REMOVE_DIALOG);
			i = new Intent();
			i.putExtra("refresh", true);
			setResult(RESULT_OK, i);
			this.finish();
			break;
		default:
			return;
		}
	}


	/**
	 * Set asynchronously the status progress
	 * 
	 * @param result
	 */
	public void setProgress(Bitmap result) {
		// Free memory
		if (bm != null) {
			bm.recycle();
		}

		// Set ImageView
		if (result != null) {
			imageView.setImageBitmap(result);
			return;
		} else
			imageView.setImageResource(android.R.drawable.ic_menu_gallery);
	}

	/**
	 * Asynchornous task to download an image from url
	 */
	private class DownloadImageTask extends AsyncTask<String, Bitmap, Bitmap> {

		private static final int PROGRESS_DIALOG = 0;

		/**
		 * Handler onPreExecute event
		 */
		protected void onPreExecute() {
			// Create an new progress dialog
			showDialog(PROGRESS_DIALOG);
		}

		/**
		 * Method executed in background thread
		 */
		protected Bitmap doInBackground(String... params) {
			Bitmap bm = null;
			for (int i = 0; i < params.length; i++) {
				ImageLoader img = new ImageLoader();
				bm = img.loader(params[i]);
				publishProgress(bm);
			}
			return bm;
		}

		@Override
		protected void onProgressUpdate(Bitmap... values) {
			super.onProgressUpdate(values);
			setProgress(values[0]);
		}

		/**
		 * Handler onPostExecute
		 */
		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			// Hide Progress Dialog
			dismissDialog(PROGRESS_DIALOG);
		}

	}
}
